package cn.lyjuan.android.demofive.ui.effect;

import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;

import cn.lyjuan.android.mylibrary.util.Logger;

public class DragFrame extends FrameLayout
{
    private int windowX;
    private int windowY;

    private boolean init = false;

    private int sx;
    private int sy;

    public DragFrame(@NonNull Context context)
    {
        super(context);
    }

    public DragFrame(@NonNull Context context, @Nullable AttributeSet attrs)
    {
        super(context, attrs);
    }

    public DragFrame(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

    private void init()
    {
        if (init) return;
        init = true;

        ViewParent p = this.getParent();
        DisplayMetrics dm = this.getContext().getResources().getDisplayMetrics();
        windowY = dm.heightPixels;
        windowX = dm.widthPixels;

        // 仅允许在父视图内移动
        if (ViewGroup.class.isAssignableFrom(p.getClass()))
        {
            Rect r = new Rect();
            ViewGroup v = (ViewGroup) p;
            v.getDrawingRect(r);
            windowX = Math.min(r.width(), windowX);
            windowY = Math.min(r.height(), windowY);
        } else
        {
            int[] xy = new int[2];
            this.getLocationOnScreen(xy);
            windowY -= (xy[1] - this.getY());
        }

        // 减去控件自身的大小
        windowX -= this.getMeasuredWidth();
        windowY -= this.getMeasuredHeight();
        Logger.d("init windowX-" + windowX + " windownY-" + windowY);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        init();

        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:// 按下时
                sx = (int) event.getRawX();
                sy = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:// 移动时
                int x = (int) event.getRawX();
                int y = (int) event.getRawY();
                // 获取手指移动的距离
                int dx = x - sx;
                int dy = y - sy;
                // 获取移动后的位置
                sx = (int) event.getRawX();
                sy = (int) event.getRawY();
                // 设置位置
                float rx = this.getX() + dx;
                float ry = this.getY() + dy;

                this.setX(rx > 0 ? (rx > windowX ? windowX : rx) : 0);
                this.setY(ry > 0 ? (ry > windowY ? windowY : ry) : 0);

                break;
            case MotionEvent.ACTION_UP:// 抬起时
                break;
        }

        return true;
    }
}
